package com.example.statistics.ui

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.telephony.TelephonyManager
import com.example.statistics.R
import com.example.statistics.bean.FilesBean
import com.example.statistics.bean.UserBean
import com.example.statistics.common.BaseActivity
import com.example.statistics.constant.PreferenceConstants
import com.example.statistics.ex.*
import com.example.statistics.net.DataResult
import com.example.statistics.net.UrlConfig
import com.example.statistics.net.callback.UploadDialogHttpCallback
import com.example.statistics.ui.customer.Customer
import com.example.statistics.ui.sales.SalesCustomerSearchActivity
import com.example.statistics.utils.CustomerUtils
import com.example.statistics.utils.FileUtils
import com.example.statistics.utils.permissions.PermissionsCheck
import com.google.gson.Gson
import com.jhj.httplibrary.HttpCall
import com.example.statistics.ex.contentText
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.startActivity
import java.io.File

class LoginActivity : BaseActivity() {

    private var user: UserBean? = null

    override val isTotalBarDisplay: Boolean
        get() = false

    override val title: String
        get() = ""


    @SuppressLint("HardwareIds")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        PermissionsCheck.with(this)
                .requestPermissions(android.Manifest.permission.READ_CONTACTS,
                        android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onPermissionsResult { _, _ ->
                    user = preferenceFind(UserBean::class.java, PreferenceConstants.USER)
                    if (user != null) {
                        startActivity<SalesCustomerSearchActivity>()
                        finish()
                        GlobalScope.launch {
                            val fileList = getSync<List<FilesBean>>(UrlConfig.USER_INFO_LIST, "identification" to user?.phone)
                            if (fileList.isNullOrEmpty()) {
                                CustomerUtils.query(this@LoginActivity) { list ->
                                    val folder = FileUtils.getSDPath("user")
                                    val filePath = folder + "${user?.phone}.json"
                                    val customerList = list.map { Customer(it.ID, it.name, it.phoneOne) }
                                    val customerString = Gson().toJson(customerList)
                                    createFileWithByte(customerString.toByteArray(), filePath)
                                    addFiles(filePath)
                                }
                            }
                        }
                    }
                }

        layout_commit.setOnCommitListener {
            httpPost<UserBean>(UrlConfig.USER_LOGIN, config = {
                listParams = listOf(
                        "phone" to tv_account.contentText,
                        "password" to tv_password.contentText,
                        "deviceId" to getDeviceId()
                )
            }) {
                preferenceSave(it, "user")
                startActivity<SalesCustomerSearchActivity>()
                finish()
            }
        }
        tv_register.onClick {
            //startActivity<RegisterActivity>()
            // preferenceDelete(UserBean::class.java, PreferenceConstants.USER)
        }

    }


    private fun addFiles(filePath: String) {
        HttpCall.post(UrlConfig.USER_INFO_SAVE)
                .addFiles("files[]", listOf(File(filePath)))
                .addParam("identification", user?.phone)//标识
                .addParam("folder", "info")//分块（合同编号）
                .addParam("type", "customer")
                .enqueue(object : UploadDialogHttpCallback<List<FilesBean>>(this) {
                    override fun onSuccess(data: List<FilesBean>?, resultType: ResultType) {
                        val file = File(filePath)
                        if (file.exists()) {
                            file.delete()
                        }
                    }
                })
    }

    @SuppressLint("HardwareIds")
    fun getDeviceId(): String {
        var deviceId = ""
        try {
            deviceId = if (Build.VERSION.SDK_INT < 29) {
                val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?;
                if (tm != null) {
                    if (tm.deviceId == "")
                        tm.deviceId;
                    else
                        Settings.Secure.getString(this.contentResolver,
                                Settings.Secure.ANDROID_ID);
                } else
                    Settings.Secure.getString(this.contentResolver,
                            Settings.Secure.ANDROID_ID);
            } else {
                Settings.Secure.getString(this.contentResolver,
                        Settings.Secure.ANDROID_ID);
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
        return deviceId
    }

}